package cn.xiyue.boxuegu;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import cn.xiyue.boxuegu.base.BaseActivity;
import cn.xiyue.boxuegu.utils.MD5Utils;

public class RegisterActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_back;
    private TextView tv_main_title;
    private EditText et_user_name;
    private EditText et_psw;
    private EditText et_psw_again;
    private Button btn_register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }

    private void initView() {
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_main_title = (TextView) findViewById(R.id.tv_main_title);
        et_user_name = (EditText) findViewById(R.id.et_user_name);
        et_psw = (EditText) findViewById(R.id.et_psw);
        et_psw_again = (EditText) findViewById(R.id.et_psw_again);
        btn_register = (Button) findViewById(R.id.btn_register);

        tv_back.setOnClickListener(v -> finish());
        tv_main_title.setText("注 册");

        btn_register.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register:
                submit();
                break;
        }
    }

    private void submit() {
        // validate
        String name = et_user_name.getText().toString().trim();
        String psw = et_psw.getText().toString().trim();
        String again = et_psw_again.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            showMsg("请输入用户名");
        } else if (TextUtils.isEmpty(psw)) {
            showMsg("密码不能为空");
        } else if (TextUtils.isEmpty(again)) {
            showMsg("请再次输入密码");
        } else if (!psw.equals(again)) {
            showMsg("两次密码必须一致");
        } else if (isExistUserName(name)) {
            showMsg("同户名已存在");
        } else {
            showMsg("注册成功");
            getSPEditor().putString(name,MD5Utils.md5(psw)).apply();
            Intent intent = new Intent();
            intent.putExtra("userName", name);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    private boolean isExistUserName(String userName) {
        boolean hasUserName = false;
        if (!TextUtils.isEmpty(getSP().getString(userName, ""))) {
            hasUserName = true;
        }
        return hasUserName;
    }

}